package com.whjk.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.whjk.core.common.dto.PageDto;
import com.whjk.core.common.utils.PinYinUtil;

import com.whjk.system.biz.service.WhjkPersonService;
import com.whjk.system.biz.service.WhjkTeamGroupItemService;
import com.whjk.system.biz.service.WhjkTeamGroupService;
import com.whjk.system.data.dto.WhjkTeamCheckInfoDto;
import com.whjk.system.data.entity.WhjkPerson;
import com.whjk.system.data.entity.WhjkTeamCheckInfo;
import com.whjk.system.biz.mapper.WhjkTeamCheckInfoMapper;
import com.whjk.system.biz.service.WhjkTeamCheckInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whjk.system.data.entity.WhjkTeamGroup;

import com.whjk.system.data.entity.WhjkTeamGroupItem;
import com.whjk.system.data.vo.WHJKteamWaitDetailVo;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 体检单位 服务实现类
 * </p>
 *
 * @author hl
 * @since 2023-06-28
 */
@Service
public class WhjkTeamCheckInfoServiceImpl extends ServiceImpl<WhjkTeamCheckInfoMapper, WhjkTeamCheckInfo> implements WhjkTeamCheckInfoService {
    @Autowired
    private WhjkTeamGroupService whjkTeamGroupService;
    @Autowired
    private WhjkTeamGroupItemService whjkTeamGroupItemService;
    @Autowired
    private WhjkPersonService whjkPersonService;


    /**
     * 添加单位
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTeamCheckInfo(WhjkTeamCheckInfo teamCheckInfo) {
        LambdaQueryWrapper<WhjkTeamCheckInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WhjkTeamCheckInfo::getDelFlag, "0")
                .eq(WhjkTeamCheckInfo::getTeamName, teamCheckInfo.getTeamName());
        Assert.isTrue(this.baseMapper.selectCount(queryWrapper) == 0, "该公司已存在，无需添加");
        teamCheckInfo.setPinyinCode(PinYinUtil.getPinyinKt(teamCheckInfo.getTeamName()));
        this.baseMapper.insert(teamCheckInfo);
    }

    /**
     * 更新单位
     * 逻辑删除的时候需要去查看单位下是否有人员在检查
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTeamCheckInfo(WhjkTeamCheckInfo teamCheckInfo) {
        Assert.notNull(this.getById(teamCheckInfo.getId()), "单位异常");
        this.baseMapper.updateById(teamCheckInfo);
    }

    /**
     * 单位分页模糊查询
     */
    @Override
    public Page<WhjkTeamCheckInfo> queryUnit(WhjkTeamCheckInfo teamCheckInfo) {
        QueryWrapper<WhjkTeamCheckInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0)
                .like(StringUtils.isNotBlank(teamCheckInfo.getKeyword()), "team_name", teamCheckInfo.getKeyword())
                .or().like(StringUtils.isNotBlank(teamCheckInfo.getKeyword()), "team_code", teamCheckInfo.getKeyword())
                .or().like(StringUtils.isNotBlank(teamCheckInfo.getKeyword()), "short_name", teamCheckInfo.getKeyword())
                .or().like(StringUtils.isNotBlank(teamCheckInfo.getKeyword()), "pinyin_code", teamCheckInfo.getKeyword())
                .like(StringUtils.isNotBlank(teamCheckInfo.getKeyword()), "wubi_code", teamCheckInfo.getKeyword());
        return baseMapper.selectPage(new Page<>(teamCheckInfo.getCurrent(), teamCheckInfo.getSize()), queryWrapper);
    }

    /**
     * 查询所有单位下的分组及子分组
     */

    @Override
    public List<WhjkTeamCheckInfoDto> queryTeamInfoList(PageDto pageDto) {
        String keyword = pageDto.getKeyword();
        List<WhjkTeamCheckInfoDto> teamCheckInfos = this.baseMapper.selectTeamInfoList();
        List<WhjkTeamGroup> whjkTeamGroups = listTeamGroup(whjkTeamGroupService.list(new LambdaQueryWrapper<WhjkTeamGroup>().eq(WhjkTeamGroup::getDelFlag, "0")));
        if (keyword != null && !keyword.isEmpty()) {
            teamCheckInfos = teamCheckInfos.stream()
                    .filter(teamCheckInfo -> teamCheckInfo.getTeamName().contains(keyword))
                    .collect(Collectors.toList());
        }

        return teamCheckInfos.stream()
                .peek(teamCheckInfo -> {
                    List<WhjkTeamGroup> filteredTeamGroups = whjkTeamGroups.stream()
                            .filter(teamGroup -> teamGroup.getTeamId().equals(teamCheckInfo.getId()))
                            .collect(Collectors.toList());
                    teamCheckInfo.setGroupList(filteredTeamGroups);
                })
                .collect(Collectors.toList());
    }

    /**
     * 查询单个单位下的分组及子分组
     */
    @Override
    public WhjkTeamCheckInfoDto queryUnitGroup(String teamId) {
        WhjkTeamCheckInfo whjkTeamCheckInfo = this.getOne(new LambdaQueryWrapper<WhjkTeamCheckInfo>().eq(WhjkTeamCheckInfo::getId,teamId).eq(WhjkTeamCheckInfo::getDelFlag,0));
        Assert.notNull(whjkTeamCheckInfo,"该单位已被删除");
        WhjkTeamCheckInfoDto infoDto = new WhjkTeamCheckInfoDto();
        BeanUtils.copyProperties(whjkTeamCheckInfo, infoDto);
        List<WhjkTeamGroup> list = listTeamGroup(whjkTeamGroupService
                .list(new LambdaQueryWrapper<WhjkTeamGroup>().eq(WhjkTeamGroup::getDelFlag, "0")))
                .stream()
                .filter(whjkTeamGroup -> whjkTeamGroup.getTeamId().equals(teamId))
                .collect(Collectors.toList());

        infoDto.setGroupList(list);
        return infoDto;
    }

    /**
     * 待体检人数
     */
    @Override
    public Page<WhjkTeamCheckInfo> waitInspectionPerson(WhjkTeamCheckInfo team) {
        return this.baseMapper.waitInspectionPersonPage(new Page<>(team.getCurrent(), team.getSize()), new QueryWrapper<>()
                .eq("per.del_flag", 0)
                .in("per.pe_status", 0, 1)
                .like(StringUtils.isNotBlank(team.getId()),  "info.id", team.getId())
                .groupBy("info.team_name", "info.id")

        );


    }

    @Override
    public WHJKteamWaitDetailVo teamWaitDetail(String groupId) {
        WhjkTeamGroup one = whjkTeamGroupService.getOne(new LambdaQueryWrapper<WhjkTeamGroup>().eq(WhjkTeamGroup::getDelFlag, 0).eq(WhjkTeamGroup::getId, groupId));
        WHJKteamWaitDetailVo detailVo = new WHJKteamWaitDetailVo();
        BeanUtils.copyProperties(one, detailVo);
        detailVo.setZhxms(whjkTeamGroupItemService.list(new LambdaQueryWrapper<WhjkTeamGroupItem>().eq(WhjkTeamGroupItem::getDelFlag, 0).eq(WhjkTeamGroupItem::getGroupId, groupId)));
        detailVo.setWaitRegList(whjkPersonService.list(new LambdaQueryWrapper<WhjkPerson>().eq(WhjkPerson::getDelFlag, 0).eq(WhjkPerson::getGroupId, groupId).in(WhjkPerson::getPeStatus,0,1)));
        return detailVo;
    }


    /**
     * 单位下分组
     */
    public List<WhjkTeamGroup> listTeamGroup(List<WhjkTeamGroup> teamGroupList) {
        return teamGroupList.stream()
                .filter(TeamGroup -> StringUtils.isBlank(TeamGroup.getGroupId()))
                .peek(TeamGroup -> TeamGroup.setChildList(getChildTeamGroup(TeamGroup.getId(), teamGroupList)))
                .collect(Collectors.toList());
    }


    /**
     * 分组递归
     */
    public List<WhjkTeamGroup> getChildTeamGroup(String code, List<WhjkTeamGroup> teamGroupList) {
        return teamGroupList.stream()
                .filter(TeamGroup -> code.equals(TeamGroup.getGroupId()))
                .peek(TeamGroup -> TeamGroup.setChildList(getChildTeamGroup(TeamGroup.getId(), teamGroupList)))
                .collect(Collectors.toList());
    }


}
